<script setup lang="ts">
import type { IAddressPoolRule } from './types.ts'

import { v4 as uuidV4 } from 'uuid'
import AddressPoolItem from './AddressPoolItem.vue'

interface IEmit {
  (event: 'update:rules', value: IAddressPoolRule[]): void
  (event: 'change', value: IAddressPoolRule[]): void
  (event: 'delete'): void
}

interface IProps {
  last?: boolean
  disabledAll?: boolean
  rules: IAddressPoolRule[]
}

const props = withDefaults(defineProps<IProps>(), {
  last: false,
  disabledAll: false,
})
const emit = defineEmits<IEmit>()
const addressPoolRuleRefs = ref<(typeof AddressPoolItem)[]>([])

/**
 * 此组的规则列表
 */
const rules = useVModel(props, 'rules', emit)

/**
 * 此组已选择的字段列表
 */
const selectedFields = computed(() => {
  return rules.value.map(rule => rule.field)
})

/**
 * 添加规则，每个字段仅能出现一次
 */
function handleAddRule() {
  // const fields = matchConfig.map(item => item.value)
  rules.value.push({
    uuid: uuidV4(),
    id: '',
  })
}

/**
 * 删除规则，如果此组只有一个规则了，则直接删除该组
 */
function handleDeleteRule(index: number) {
  if (rules.value.length > 1) {
    rules.value.splice(index, 1)
    return
  }
  emit('delete')
}

provide('selectedFields', selectedFields)

defineExpose({
  validate() {
    return Promise.all(
      addressPoolRuleRefs.value.map(ruleComp => ruleComp.validate()),
    )
  },
})
</script>

<template>
  <div class="address-group">
    <div class="container">
      <address-pool-item
        v-for="(rule, index) in rules"
        :key="rule.uuid"
        ref="addressPoolRuleRefs"
        v-model:id="rule.id"
        :rules="rules || []"
        :disable-delete="rules.length === 1"
        :disabled-all="disabledAll"
        @add="handleAddRule"
        @delete="handleDeleteRule(index)"
      />
    </div>
    <div class="footer">
      <a-link
        type="text"
        :disabled="rules.length >= 20"
        class="!bg-transparent !px-0"
        @click="handleAddRule"
      >
        <i-icons-plus-square class="mr-1" />添加一行
      </a-link>
    </div>
  </div>
</template>

<style scoped lang="less"></style>
